<template>
  <div class="log-page">
    <!-- 查询条件 -->

    <el-card class="box-card">
      <h3>查询条件</h3>
        <el-form :inline="true" :model="searchForm" class="search-form" >
          <el-form-item label="账号：">
            <el-input v-model="searchForm.username" placeholder="请输入账号" clearable />
          </el-form-item>
          <el-form-item label="用户昵称：">
            <el-input v-model="searchForm.nickname" placeholder="请输入昵称" clearable />
          </el-form-item>
          <el-form-item label="注册日期：">
            <el-date-picker
                v-model="searchForm.createTime"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                unlink-panels
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
    </el-card>

    <!-- 日志列表 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <h3>用户列表</h3>
      <div style="margin-bottom: 10px;">
        <el-button size="default" type="primary" icon="Remove" @click="onBan">封禁</el-button>
        <el-button size="default" type="danger" icon="Delete" @click="onDelete">批量删除</el-button>
      </div>



      <el-table
          :data="logList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="用户ID" width="100" />
        <el-table-column prop="username" label="用户账号" width="120" />
        <el-table-column prop="nickname" label="用户昵称" width="120" />
        <el-table-column prop="userLevel" label="会员等级" width="180" />
        <el-table-column prop="accountBalance" label="账号余额" width="180" />
        <el-table-column prop="createTime" label="注册日期"  />

        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button @click="toDetail(scope.row.id)" type="primary" link size="default">查看</el-button>
            <el-button @click="toEdit(scope.row.id)" type="primary" link size="default">编辑</el-button>
            <el-button @click="removePreUser(scope.row.id)" type="primary" link size="default">删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="total"
            layout="total, prev, pager, next, sizes, jumper"
            :page-sizes="[5, 10, 20, 50]"
            background
            @current-change="handlePageChange"
            @size-change="handlePageSizeChange"
        />
      </div>
    </el-card>


    <el-dialog v-model="showBanDialog" title="账号封禁" width="30%">
      <p>账号：{{usernames}}</p>
      <el-form-item label="封禁原因：" prop="banReason">
        <el-input v-model="banReason" placeholder="请输入封禁原因"></el-input>
      </el-form-item>
      <el-radio-group v-model="banType">
        <el-radio  :label=1>临时封禁</el-radio>
        <el-radio :label=2>永久封禁</el-radio>
      </el-radio-group>
      <el-form v-if="banType === 1" inline label-width="60px">
        <el-form-item label="年">
          <el-select v-model="duration.years" placeholder="0" style="width: 80px">
            <el-option v-for="n in 6" :key="n-1" :label="n-1" :value="n-1" />
          </el-select>
        </el-form-item>
        <el-form-item label="月">
          <el-select v-model="duration.months" placeholder="0" style="width: 80px">
            <el-option v-for="n in 12" :key="n-1" :label="n-1" :value="n-1" />
          </el-select>
        </el-form-item>
        <el-form-item label="天">
          <el-select v-model="duration.days" placeholder="0" style="width: 80px">
            <el-option v-for="n in 31" :key="n-1" :label="n-1" :value="n-1" />
          </el-select>
        </el-form-item>
        <el-form-item label="小时">
          <el-select v-model="duration.hours" placeholder="0" style="width: 80px">
            <el-option v-for="n in 24" :key="n" :label="n-1" :value="n-1" />
          </el-select>
        </el-form-item>
        <el-form-item label="分钟">
          <el-select v-model="duration.minutes" placeholder="0" style="width: 80px">
            <el-option v-for="n in 60" :key="n" :label="n-1" :value="n-1" />
          </el-select>
        </el-form-item>
        <el-form-item label="秒">
          <el-select v-model="duration.seconds" placeholder="0" style="width: 80px">
            <el-option v-for="n in 60" :key="n" :label="n-1" :value="n-1" />
          </el-select>
        </el-form-item>
      </el-form>



      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showBanDialog = false">取消</el-button>
          <el-button type="primary" @click="handleBanConfirm">保存</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'
import {router} from "@/router/index.js"
import dayjs from "dayjs";


// ==============================================================
const showBanDialog = ref(false);
const banType = ref(1);
const banDays = ref('');
const banReason  =ref('');



const usernames  =ref("");
const onBan = () => {
  if (selectedLogs.value.length === 0) {
    ElMessage.warning('请选择要封禁的用户')
    return
  }
  const ids = selectedLogs.value.map(log => log.id);
  usernames.value  =selectedLogs.value.map(user => user.username).join(",");
  showBanDialog.value = true;
  // dialogVisible.value = true;
  // ElMessageBox.confirm(
  //     '此操作将封禁选中的用户，是否继续？',
  //     '警告',
  //     {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     }
  // )
  //     .then(() => {
  //
  //     })
  //     .catch(() => {
  //       ElMessage.info('已取消封禁');
  //     });
}

const duration = ref({
  years: 0,
  months: 0,
  days: 0,
  hours: 0,
  minutes: 0,
  seconds: 0,
});

const handleBanConfirm = () => {
  const d = duration.value;
  const total = d.years + d.months + d.days + d.hours + d.minutes + d.seconds;

  
  if(banType.value === 1 && total === 0){
    ElMessage.error('请至少选择一个封禁时长');
    return
  }


  const banUntil = dayjs()
      .add(d.years, 'year')
      .add(d.months, 'month')
      .add(d.days, 'day')
      .add(d.hours, 'hour')
      .add(d.minutes, 'minute')
      .add(d.seconds, 'second')
      .format('YYYY-MM-DD HH:mm:ss');

  const payload = {
    userIds: selectedLogs.value.map(u => u.id),
    banType: banType.value,
    banReason: banReason.value,
    banStartTime: dayjs(),
    banEndTime: banUntil,
  };

  console.log('封禁参数:', payload);
  ElMessage.success(`封禁成功，截止时间：${banUntil}`);
  showBanDialog.value = false;
};
// ==============================================================





const toDetail = (id) => {
  router.push("/preUserDetail?id="+id)
}

const toEdit = (id) => {
  router.push(`/editPreUserForm?id=`+id)
}

const searchForm = ref({
  username: '',
  nickname: '',
  createTime: [],
})

const logList = ref([]) // 后台返回的日志数据
const total = ref(0) // 总记录数

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
})

// 查询日志列表
const fetchLogList =  () => {
  // try {
  const { currentPage, pageSize } = pagination.value
  axios.post(`/user/getAllPreUser/${currentPage}/${pageSize}`, {

    username: searchForm.value.username|| undefined,
    nickname: searchForm.value.nickname|| undefined,
    startTime: searchForm.value.createTime[0] || undefined,
    endTime: searchForm.value.createTime[1] || undefined,

  }).then(resp=>{
    logList.value = resp.data.records;
    console.log(logList.value);
    total.value = resp.data.total;
  })
}

// 查询按钮点击
const onSearch = () => {
  pagination.value.currentPage = 1;

  fetchLogList()
}

// 重置查询条件
const onReset = () => {
  searchForm.value.username = ''
  searchForm.value.nickname = ''
  searchForm.value.createTime = []
  onSearch()
}

// 分页变化
const handlePageChange = (newPage) => {
  pagination.value.currentPage = newPage
  fetchLogList()
}
const handlePageSizeChange = (newSize) => {
  pagination.value.pageSize = newSize
  pagination.value.currentPage = 1
  fetchLogList()
}

// 多选项变化
const selectedLogs = ref([])
//
const handleSelectionChange = (selection) => {
  selectedLogs.value = selection
}

// 删除（模拟）

const onDelete = () => {
  if (selectedLogs.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  const ids = selectedLogs.value.map(log => log.id);
  ElMessageBox.confirm(
      '此操作将永久删除所选，是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        axios.post("/user/batchRemPreUser", ids).then(resp => {
          if (resp.data) {
            ElMessage.success('删除成功');
            fetchLogList(); // 重新拉取日志列表
          } else {
            ElMessage.error('删除失败');
          }
        }).catch(() => {
          ElMessage.error('请求失败，请稍后重试');
        });
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
}

const removePreUser = (id) => {
  ElMessageBox.confirm(
      '此操作将永久删除该用户，是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        axios.post(`/user/removePreUser/${id}`).then(resp => {
          if (resp.data) {
            ElMessage.success('删除成功');
            fetchLogList(); // 重新拉取日志列表
          } else {
            ElMessage.error('删除失败');
          }
        }).catch(() => {
          ElMessage.error('请求失败，请稍后重试');
        });
      })
      .catch(() => {
        ElMessage.info('已取消');
      });
}





// 初始化加载
onMounted(() => {
  fetchLogList()
})
</script>

<style scoped>
.log-page {
  padding: 20px;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
